<template>
	<div>
        <el-card class="!border-none" shadow="never">
            <el-button v-perms="['city.manage/add']" type="primary" class="mb-4" @click="hanldeAdd">
                <template #icon>
                    <icon name="el-icon-Plus"/>
                </template>
                新增城市
            </el-button>
            <el-table size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="序号" type="index" min-width="80" :index="indexAdd" />
                <el-table-column label="省名称" min-width="180" prop="prov_name"/>
                <el-table-column label="城市名称" min-width="180" prop="area_name"/>
                <el-table-column label="区划代码" min-width="180" prop="area_id"/>
                <el-table-column label="下级行政区划" min-width="180" prop="name"/>
                <el-table-column label="管理员姓名" min-width="180" prop="caad_name"/>
                <el-table-column label="管理员手机号" min-width="180" prop="caad_account"/>
                <el-table-column label="状态" min-width="120" prop="user_type">
                    <template #default="{ row }">
                        <span v-if="row.is_enable == 1">启用</span>
                        <el-link v-else type="danger" :underline="false">停用</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="创建人" min-width="180" prop="ad_name"/>
                <el-table-column label="创建时间" min-width="180" prop="create_time"/>
                <el-table-column label="操作" width="240" fixed="right">
                    <template #default="{ row }">
                        <el-link class="link" v-perms="['city.manage/edit']" type="primary" :underline="false" @click="handleEdit(row)">修改</el-link>
                        <el-link class="link" v-perms="['city.manage/delete']" type="danger" :underline="false" @click="handleDelGroup(row)">删除</el-link>
                        <el-link v-if="row.is_enable != 1" class="link" v-perms="['city.manage/updateStatus']" type="primary" :underline="false" @click="handleOpen(row)">启用</el-link>
                        <el-link v-if="row.is_enable == 1" class="link" v-perms="['city.manage/updateStatus']" type="danger" :underline="false" @click="handleClose(row)">停用</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <el-dialog
                v-model="showCity"
                :title="formData.id?'编辑城市':'新增城市'"
                width="500"
                @close="handleDiaClose"
            >
                <el-form
                    ref="formRef"
                    :model="formData"
                    :rules="rules"
                    label-width="130"
                    require-asterisk-position="right"
                >
                    <el-form-item label="城市名称" prop="area_name">
                        <div class="w-80">
                            <el-select v-model="formData.area_name" placeholder="请选择" filterable @change="onChange">
                                <template v-for="item in cityList" :key="item.ID">
                                    <el-option
                                        v-if="item.ID !== ''"
                                        :label="item.Name"
                                        :value="item.ID"
                                    ></el-option>
                                </template>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="区划代码" prop="area_id">
                        <div class="w-80">
                            <el-input
                                v-model="formData.area_id"
                                placeholder="区划代码"
                                type="text"
                                maxlength="15"
                                show-word-limit
                                clearable
                                readonly
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label="管理员姓名" prop="name">
                        <div class="w-80">
                            <el-input
                                v-model="formData.name"
                                placeholder="请输入管理员姓名"
                                type="text"
                                maxlength="15"
                                show-word-limit
                                clearable
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label="管理员手机号" prop="account">
                        <div class="w-80">
                            <el-input
                                v-model="formData.account"
                                placeholder="请输入管理员手机号"
                                type="text"
                                maxlength="11"
                                show-word-limit
                                clearable
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label="管理员密码" prop="password">
                        <div class="w-80">
                            <el-input
                                v-model="formData.password"
                                placeholder="请输入管理员密码"
                                type="password"
                                minlength="8"
                                show-password
                                clearable
                            />
                            <div class="tip">不少于8位，至少包含数字、字母、符号中的2种；</div>
                        </div>
                    </el-form-item>
                    <el-form-item label="状态" prop="is_enable">
                        <div class="w-80">
                            <el-radio-group v-model="formData.is_enable" class="ml-4">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="0">停用</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="onCancel">取消</el-button>
                        <el-button type="primary" @click="onSubmit" :loading="loading">确认</el-button>
                    </div>
                </template>
            </el-dialog>
    </div>
</template>
<script lang="ts" setup name="demandLists">
    import { getAllCity, lists, add, edit, updateStatus, cityDelete } from '@/api/city';
	import { usePaging } from '@/hooks/usePaging';
    import { getRoutePath } from '@/router'
    import feedback from '@/utils/feedback'
    import type {FormInstance} from 'element-plus';

	let queryParams:any = reactive({

	});

    const showCity = ref(false);
    const formData = reactive({
        id: '',
        area_name: '',
        area_id: '',
        name: '',
        account: '',
        password: '',
        is_enable: 1
    })
    const formRef = shallowRef<FormInstance>()
    const rules = reactive({
        area_name: [{required: true, message: '请选择城市名称', trigger: 'blur'}],
        area_id: [{required: true, message: '请先选择城市名称', trigger: 'blur'}],
        name: [{required: true, message: '请填写管理员姓名', trigger: 'blur'}],
        account: [
            {required: true, message: '请填写管理员手机号', trigger: 'blur'},
            {pattern: /^1[3456789]\d{9}$/, message: '请填写正确的手机号', trigger: ['blur', 'change'] }
        ],
        password: [{min: 8, required: true, message: '请填写不少于8位的密码', trigger: 'blur'}],
        is_enable: [{required: true, message: '请选择状态', trigger: 'blur'}],
    })
	
	onMounted(async () => {
		getLists();
	});

    const hanldeAdd = async () => {
        let obj = {
            id: '',
            area_name: '',
            area_id: '',
            name: '',
            account: '',
            password: '',
            is_enable: 1
        }
        Object.keys(formData).forEach((key) => {
            //@ts-ignore
            formData[key] = obj[key]
        })
        rules.password = [{min: 8, required: true, message: '请填写不少于8位的密码', trigger: 'blur'}]
        loading.value = false;
        showCity.value = true;
        setTimeout(function () {
            formRef.value?.clearValidate();//消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        },30);
    }

    const handleEdit = (row:any) => {
        Object.keys(formData).forEach((key) => {
            //@ts-ignore
            formData[key] = row[key]
        })
        formData.id = row.id;
        formData.name = row.caad_name;
        formData.account = row.caad_account;
        formData.password = ''
        rules.password = []
        loading.value = false;
        showCity.value = true;
    }

    const handleDelGroup = async (row:any) => {
        console.log(row)
        try{
			await feedback.confirm('确认删除所选城市？')
			await cityDelete({
				id: row.id
			})
            getLists();
		}catch(error){
			console.log(error)
		}
    }

    const handleOpen = async (row:any) => {
        try{
			await feedback.confirm('启用之后，有关该场地的所有信息（场地、工位、会议室、第三方服务等）将在助融圈中显示，是否确认启用？')
			await updateStatus({
				id: row.id,
                is_enable: 1
			})
            getLists();
		}catch(error){
			console.log(error)
		}
    }
    const handleClose = async (row:any) => {
        try{
			await feedback.confirm('停用之后助融圈内有关该场地的所有信息（场地、工位、会议室、第三方服务等）将不再显示，是否确认停用？')
			await updateStatus({
				id: row.id,
                is_enable: 0
			})
            getLists();
		}catch(error){
			console.log(error)
		}
    }

	// 切页序号变化
    const indexAdd = (index: number) => {
        const page = pager.page // 当前页码
        const pagesize = pager.size // 每页条数
        return index + 1 + (page - 1) * pagesize
    }
	const { pager, getLists, resetPage, resetParams } = usePaging({
		fetchFun: lists,
		params: queryParams
	})

    const cityList:any = ref([])
    const getCity = async() => {
        const res = await getAllCity()
        cityList.value = res;
    }

    const onChange = (value: any) => {
        console.log(value)
        formData.area_id = value;
    }
    const handleDiaClose = () => {
        console.log('===')
        setTimeout(function () {
            formRef.value?.clearValidate();//消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        },30);
    }
    const onCancel = () => {
        setTimeout(function () {
            formRef.value?.clearValidate();//消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        },30);
        showCity.value = false
    }
    const loading = ref(false)
    const onSubmit = async() => {
        try{
            await formRef.value?.validate()
            loading.value = true;
            console.log(formData)
            if (formData.id) {
                await edit(formData)
            } else {
                await add(formData)
            }
            
            showCity.value = false;
            getLists()
        }catch(error){
            console.log(error)
        }
    }

    getCity()
</script>
<style lang="scss" scoped>
.content{
    width: 360px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
.w-80{
    ::v-deep .el-select{
        width: 100%;
    }
}
.link{
    margin: 0 10px;
}
.tip{
    color: #999999;
}
</style>